﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Reddit.Data;
using System.Runtime.Serialization.Json;

namespace Reddit
{
    namespace JsonParser
    {
        public class RedditJsonParser : IJsonParser
        {

            //TODO: this works, but i hate it
            protected DataContractJsonSerializer GetDataContainerCollectionSerializer<T>()
            {
                DataContainerCollection obj = Activator.CreateInstance<T>() as DataContainerCollection;
                return new DataContractJsonSerializer(typeof(T),
                    null,
                    100000,//?
                    false,
                    new ArrayDataContractSurrogate(typeof(DataContainer), obj.Types),
                    false);
            }

            public T Parse<T>(string json)
                where T : class
            {
                try
                {
                    DataContractJsonSerializer serializer;
                    if (typeof(T).IsSubclassOf(typeof(DataContainerCollection))) //TODO: fix
                    {
                        serializer = this.GetDataContainerCollectionSerializer<T>();
                    }
                    else
                    {
                        serializer = new DataContractJsonSerializer(typeof(T));
                    }
                    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
                    T obj = (T)serializer.ReadObject(ms);
                    ms.Close();
                    return obj;
                }
                catch (System.Runtime.Serialization.SerializationException e)
                {
                    throw new JsonParseException("Could not parse json", e);
                }
            }
        }
    }
}